package com.basin.common.feign.config;

import com.basin.common.feign.interceptor.FeignRequestInterceptor;
import com.basin.common.feign.properties.BasinBasicProp;
import com.fasterxml.jackson.databind.ObjectMapper;
import feign.*;
import feign.codec.DecodeException;
import feign.codec.Decoder;
import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;

import java.io.IOException;
import java.lang.reflect.Type;

/**
 * @author: Sam ZHONG | sammy1997@aliyun.com
 */
public class OpenFeignConfig {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Resource
    private BasinBasicProp basinBasicProp;

    @Bean
    Logger.Level level() {
        return Logger.Level.FULL;
    }

    @Bean
    public Decoder feignDecoder() {
        return new Decoder() {
            @Override
            public Object decode(Response response, Type type) throws IOException, DecodeException, FeignException {
                if (response.body() == null) {
                    return null;
                }
                String body = Util.toString(response.body().asReader());
                return objectMapper.readValue(body, objectMapper.constructType(type));
            }
        };
    }

    @Bean
    public RequestInterceptor requestInterceptor() {
        return new FeignRequestInterceptor(basinBasicProp);
    }
}
